/**
 * @Author: LiMeng
 * @Date: 2017/5/18
 */
var GLOBAL = {
    CHECK_INFO_ID: $.getQueryParam('checkInfoId'),
    ACTION_URL: ROOT_PATH + '/securityCheck/checkProblem/add.shtml',
    CONTRACTOR_ID: '',
    RISK_REGION_ID: '',
    SPECIALTY_TYPE_CODE: ''
};
var ajaxSuccessHandler = function (result) {
    result = $.parseJSON(result);
    if (result.success) {
        layer.msg(result.message, {time: 1000, icon: 1}, function () {
            WindowManager.closeLayer({returnValue: true});
        });
    } else {
        layer.msg(result.message, {icon: 2});
    }
};
var addCommonFormParams = function (param) {
    var $receiveDeptIds = $('#receiveDeptIds');
    if ($receiveDeptIds.textbox('textbox').is(':visible')) {
        param.receiveDeptNames = $receiveDeptIds.combo('getText');
    }
    param.riskPointName = $('#riskPointId').combo('getText');
    param.specialtyTypeName = $('#specialtyTypeId').combo('getText');
    param.problemTypeName = $('#problemTypeId').combo('getText');
    param.checkInfoId = GLOBAL.CHECK_INFO_ID;
};
var formSubmitAction = function (url, callback, params) {
    $.messager.progress();	// 显示进度条

    $('#form1').form('submit', {
        url: url,
        onSubmit: function (param) {
            addCommonFormParams(param);
            if ($.isNotEmpty(params)) {
                $.extend(param, params);
            }
            var isValid = $(this).form('validate');
            if (!isValid) {
                $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
            }
            return isValid;	// 返回false终止表单提交
        },
        success: function (result) {
            $.messager.progress('close');	// 如果提交成功则隐藏进度条
            callback(result);
        }
    });
};
var getSelectedContractorAudit = function (data) {
    data = data[0];
    $('#contractorAuditName').textbox('setValue', data.contractorName);
    $('#contractorAuditId').val(data.id);
    GLOBAL.CONTRACTOR_ID = data.contractorId;
};
var getSelectedProject = function (data) {
    data = data[0];
    $('#projectName').textbox('setValue', data.name);
    $('#projectId').val(data.id);
};
var getSelectedContractorStaff = function (data, target) {
    if (target === null || target === '') {
        return;
    }
    var names = '';
    var ids = '';
    for (var index in data) {
        names += ',' + data[index].name;
        ids += ',' + data[index].id;
    }

    $('#' + target + 'Names').textbox('setValue', names.substring(1));
    $('#' + target + 'Ids').val(ids.substring(1));
};
var getSelectedRiskRegion = function (data) {
    $('#riskRegionName').textbox('setValue', data.name);
    $('#riskRegionId').val(data.id);
    GLOBAL.RISK_REGION_ID = data.id;
    $('#riskPointId').combobox('reload');
};
var getSelectedRectifyUser = function (data) {
    data = data[0];
    $('#rectifyUserName').textbox('setValue', data.realName);
    $('#rectifyUserId').val(data.id);
};
var openSelectUser = function (title, callback) {
    WindowManager.openLayer({
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml',
        callBack: callback
    });
};
var openSelectContractorStaff = function (title, target) {
    title = title || '请选择承包商人员';
    target = target || '';
    if (GLOBAL.CONTRACTOR_ID === '') {
        layer.alert('请先选择承包商！');
        return;
    }
    WindowManager.openLayer({
        type: 2,
        title: title,
        area: ['700px', '400px'],
        content: ROOT_PATH + '/contractor/contractorStaff/simpleList.shtml?contractorId=' + GLOBAL.CONTRACTOR_ID + '&isMulti=1',
        callBack: function (data) {
            getSelectedContractorStaff(data, target);
        }
    });
};
var loadComboBoxData = function (success, url) {
    $(this).combobox('clear');
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        success: function (result) {
            success(result);
        }
    });
};
$(function () {

    $('#isCheckContractor').combobox({
        onChange: function (newVal) {
            var $rectifyTypeVal = $('#rectifyType').combo('getValue');
            var $isProblem = $('#isProblem').combo('getValue');
            var $contractor = $('.contractor');
            var $department = $('.department');
            var $rectifyUser = $('.rectifyUser');
            var $rectifyStaff = $('.rectifyStaff');
            if (newVal === '0') {//检查部门
                $contractor.addClass('hide').find('.textbox-f').textbox('disable');
                $department.removeClass('hide').find('.textbox-f').textbox('enable');
                $contractor.find('input').prop('disabled', true);
                $department.find('input').prop('disabled', false);
                if ($rectifyTypeVal === '1') {//立即整改
                    $rectifyStaff.addClass('hide').find('.textbox-f').textbox('disable');
                    $rectifyStaff.find('input').prop('disabled', true);
                    if ($isProblem === '1') {//计入问题
                        $rectifyUser.removeClass('hide').find('.textbox-f').textbox('enable');
                        $rectifyUser.find('input').prop('disabled', false);
                    } else {
                        $rectifyUser.removeClass('hide');
                    }
                }
            } else {//检查承包商
                $contractor.removeClass('hide').find('.textbox-f').textbox('enable');
                $department.addClass('hide').find('.textbox-f').textbox('disable');
                $contractor.find('input').prop('disabled', false);
                $department.find('input').prop('disabled', true);
                if ($rectifyTypeVal === '1' && $isProblem === '1') {//立即整改、计入问题
                    $rectifyUser.addClass('hide').find('.textbox-f').textbox('disable');
                    $rectifyUser.find('input').prop('disabled', true);
                    if ($isProblem === '1') {//计入问题
                        $rectifyStaff.removeClass('hide').find('.textbox-f').textbox('enable');
                        $rectifyStaff.find('input').prop('disabled', false);
                    } else {
                        $rectifyStaff.removeClass('hide');
                    }
                }
            }
        }
    });

    $('#isProblem').combobox({
        onChange: function (newVal) {
            var $remarks = $('#remarks');
            var $specialtyTypeId = $('#specialtyTypeId');
            var $problemTypeId = $('#problemTypeId');
            var $rectifyType = $('#rectifyType');
            var $rectifyStaffNames = $('#rectifyStaffNames');
            var $rectifyStaffIds = $('#rectifyStaffIds');
            var $rectifyUserName = $('#rectifyUserName');
            var $rectifyUserId = $('#rectifyUserId');
            var $rectifyRemarks = $('#rectifyRemarks');
            if (newVal === '0') {//不计入问题
                $remarks.textbox('disable');
                $specialtyTypeId.textbox('disable');
                $problemTypeId.textbox('disable');
                $rectifyType.textbox('disable');
                $rectifyStaffNames.textbox('disable');
                $rectifyStaffIds.prop('disabled', false);
                $rectifyUserName.textbox('disable');
                $rectifyUserId.prop('disabled', true);
                $rectifyRemarks.textbox('disable');
            } else {//计入问题
                $remarks.textbox('enable');
                $specialtyTypeId.textbox('enable');
                $problemTypeId.textbox('enable');
                $rectifyType.textbox('enable');
                if ($rectifyStaffNames.textbox('textbox').is(':visible')) {
                    $rectifyStaffNames.textbox('enable');
                    $rectifyStaffIds.prop('disabled', false);
                }
                if ($rectifyUserName.textbox('textbox').is(':visible')) {
                    $rectifyUserName.textbox('enable');
                    $rectifyUserId.prop('disabled', false);
                }
                if ($rectifyRemarks.textbox('textbox').is(':visible')) {
                    $rectifyRemarks.textbox('enable');
                }
            }
        }
    });

    $('#rectifyType').combobox({
        onChange: function (newVal) {
            if (newVal === '0') {//流程整改
                $('.work-task').removeClass('hide');
                $('#rectifyStaffNames').textbox('disable').parents('.form_one').addClass('hide');
                $('#rectifyStaffIds').prop('disabled', false);
                $('#rectifyUserName').textbox('disable').parents('.form_one').addClass('hide');
                $('#rectifyUserId').prop('disabled', true);
                $('#rectifyRemarks').textbox('disable').parents('.form_one').addClass('hide');
            } else if ($('#isCheckContractor').combo('getValue') === '0') {//立即整改(检查部门)
                $('.work-task').addClass('hide');
                $('#rectifyUserName').textbox('enable').parents('.form_one').removeClass('hide');
                $('#rectifyUserId').prop('disabled', false);
                $('#rectifyRemarks').textbox('enable').parents('.form_one').removeClass('hide');
            } else {//立即整改（检查承包商）
                $('.work-task').addClass('hide');
                $('#rectifyStaffNames').textbox('enable').parents('.form_one').removeClass('hide');
                $('#rectifyStaffIds').prop('disabled', false);
                $('#rectifyRemarks').textbox('enable').parents('.form_one').removeClass('hide');
            }
        }
    });

    $('#contractorAuditName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                WindowManager.openLayer({
                    type: 2,
                    title: '选择承包商',
                    area: ['700px', '400px'],
                    content: ROOT_PATH + '/contractor/contractorAudit/auditedList.shtml',
                    callBack: getSelectedContractorAudit
                });
            }
        }],
        editable: false
    });

    $('#receiveDeptIds').combotree({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml?parentId=0',
        required: true,
        multiple: true,
        cascadeCheck: false,
        editable: false,
        disabled: true
    });

    $('#projectName').textbox({
        editable: false,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                WindowManager.openLayer({
                    type: 2,
                    title: '选择项目',
                    area: ['800px', '300px'],
                    content: ROOT_PATH + '/threeSimultaneities/projectInfo/projectQueryList.shtml',
                    callBack: getSelectedProject
                });
            }
        }]
    });

    $('#violatedStaffNames').textbox({
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择承包商违章人员', 'violatedStaff');
            }
        }],
        editable: false
    });

    $('#rectifyResponsibleNames').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择承包商整改责任人', 'rectifyResponsible');
            }
        }],
        editable: false
    });

    $('#riskRegionName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                WindowManager.openLayer({
                    type: 2,
                    title: '选择风险区域',
                    area: ['1150px', '70%'],
                    content: ROOT_PATH + '/risk/region/simpleList.shtml',
                    callBack: getSelectedRiskRegion
                });
            }
        }],
        editable: false
    });

    $('#riskPointId').combobox({
        valueField: 'id',
        editable: false,
        loader: function (param, success) {
            if (GLOBAL.RISK_REGION_ID === '') {
                return false;
            }
            loadComboBoxData.call(this, success, ROOT_PATH + '/risk/region/point/queryComboboxList.shtml?regionId=' + GLOBAL.RISK_REGION_ID);
        }
    });

    $('#specialtyTypeId').combobox({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml?code=' + CONSTANT.DictionaryTypeDefConstants.PROBLE_TYPE,
        valueField: 'id',
        required: true,
        editable: false,
        onSelect: function (record) {
            GLOBAL.SPECIALTY_TYPE_CODE = record.code;
            $('#problemTypeId').combobox('reload');
        }
    });

    $('#problemTypeId').combobox({
        required: true,
        editable: false,
        valueField: 'id',
        loader: function (param, success) {
            if (GLOBAL.SPECIALTY_TYPE_CODE === '') {
                return false;
            }
            loadComboBoxData.call(this, success, ROOT_PATH + '/permission/dictionary/queryDictionaryByDatas.shtml?data1=' + GLOBAL.SPECIALTY_TYPE_CODE);
        }
    });

    $('#rectifyStaffNames').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择整改人', 'rectifyStaff');
            }
        }],
        editable: false
    });

    $('#rectifyUserName').textbox({
        disabled: true,
        required: true,
        editable: false,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectUser('选择整改人', getSelectedRectifyUser);
            }
        }]
    });

    //初始化加载datagrid
    $('#dg1').datagrid({
        method: 'post',
        //url: ROOT_PATH + '/securityCheck/checkProblem/list.shtml',
        data:[],
        queryParams: {
            checkInfoId: GLOBAL.CHECK_INFO_ID,
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        columns: [[
            {field: 'id', hidden: true},
            {field: 'action', title: '操作', width: 200},
            {field: 'name', title: '任务名称', width: 120},
            {field: 'rectifyDeptName', title: '整改单位', width: 120},
            {field: 'rectifyUserName', title: '整改人', width: 100},
            {field: 'rectifyDate', title: '整改期限', width: 80},
            {field: 'rectifyRemarks', title: '整改要求', width: 80}
        ]],
        onLoadSuccess: function () {
            $('.work-task').addClass('hide');
        }
    });

    $('#btn_save').on('click', function () {
        formSubmitAction(GLOBAL.ACTION_URL, ajaxSuccessHandler);
    });
});